package com.vastio.boot.realm;

import com.vastio.boot.entity.User;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;

import java.nio.charset.StandardCharsets;

/**
 * @author hjwStart
 * @time 2022-12-01 10:59
 * @version: 1.0
 */
public class MyRealm extends AuthorizingRealm {
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        return null;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {

        // AuthenticationToken的UsernamePasswordToken实现类：：getPrincipal 等价于 getUsername方法，都是获取用户的用户名
        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
        String userName = token.getUsername();
        String userPwd = token.getCredentials().toString();
        User user = User.builder()
                .userName(userName)
                .userPwd(userPwd)
                .build();
        if ("admin".equals(userName)) {
            return new SimpleAuthenticationInfo(user,
                    "79ae1231b5934424660a8e5f2aa91393",
                    ByteSource.Util.bytes("salt".getBytes(StandardCharsets.UTF_8)),
                    this.getName());
        }
        return null;
    }
}
